package LC;

import java.util.HashSet;

/**
 * https://leetcode.com/problems/valid-sudoku/description/
 * Determine if a Sudoku is valid,
 * according to: Sudoku Puzzles - The Rules.
 * The Sudoku board could be partially filled,
 * where empty cells are filled with the character '.'.
 * A partially filled sudoku which is valid.
 * Note:
 * A valid Sudoku board (partially filled) is not necessarily solvable.
 * Only the filled cells need to be validated.
 */
public class LC_036_ValidSudoku_HashSet_Math {
    public static void main(String[] args) {

    }

    static class Solution {
        public static boolean isValidSudoku(char[][] board) {
            for (int i = 0; i < 9; i++) {
                HashSet<Character> row = new HashSet<>();
                HashSet<Character> column = new HashSet<>();
                HashSet<Character> cube = new HashSet<>();

                for (int j = 0; j < 9; j++) {
                    if (board[i][j] != '.' && !row.add(board[i][j])) return false;
                    if (board[j][i] != '.' && !column.add(board[j][i])) return false;
                    int RowIndex = 3 * (i / 3) + j / 3;
                    int ColIndex = 3 * (i % 3) + j % 3;
                    if (board[RowIndex][ColIndex] != '.' && !cube.add(board[RowIndex][ColIndex])) return false;
                }

            }
            return true;
        }
    }

    static class Solution_2 {
        public static boolean isValidSudoku(char[][] board) {
            for (int i = 0; i < 9; i++) {
                int[] bit_map_row = new int[9];
                int[] bit_map_col = new int[9];
                int[] bit_map_cube = new int[9];

                for (int j = 0; j < 9; j++) {
                    if (board[i][j] != '.') {
                        if (bit_map_row[board[i][j] - '1'] == 1) return false;
                        else bit_map_row[board[i][j] - '1'] = 1;
                    }
                    if (board[j][i] != '.') {
                        if (bit_map_col[board[j][i] - '1'] == 1) return false;
                        else bit_map_col[board[j][i] - '1'] = 1;
                    }
                    int RowIndex = 3 * (i / 3) + j / 3;
                    int ColIndex = 3 * (i % 3) + j % 3;
                    int val = board[RowIndex][ColIndex];
                    if (val != '.') {
                        if (bit_map_cube[val - '1'] == 1) return false;
                        else bit_map_cube[val - '1'] = 1;
                    }
                }
            }
            return true;
        }
    }
}
